import React, { useState } from 'react';
import { useTheme } from '../contexts/ThemeContext';
import { themes } from '../config/themes';
import type { ThemeId } from '../types/theme';

const ThemeSelector: React.FC = () => {
  const { themeId, setTheme } = useTheme();
  const [isOpen, setIsOpen] = useState(false);

  const handleThemeChange = (newThemeId: ThemeId) => {
    setTheme(newThemeId);
    setIsOpen(false);
  };

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="w-10 h-10 rounded-lg flex items-center justify-center text-white/70 hover:bg-white/20 hover:text-white transition-colors"
        title="切换主题"
      >
        <i className="i-mdi-palette text-xl"></i>
      </button>

      {isOpen && (
        <>
          {/* 遮罩层 */}
          <div 
            className="fixed inset-0 z-10" 
            onClick={() => setIsOpen(false)}
          ></div>
          
          {/* 下拉菜单 */}
          <div className="absolute left-full top-0 ml-2 w-48 bg-white dark:bg-secondary-800 border border-gray-200 dark:border-secondary-600 rounded-lg shadow-lg z-20">
            <div className="p-2">
              <div className="text-xs font-medium text-gray-500 dark:text-secondary-400 px-2 py-1 mb-1">
                选择主题
              </div>
              {themes.map((themeOption) => (
                <button
                  key={themeOption.id}
                  onClick={() => handleThemeChange(themeOption.id as ThemeId)}
                  className={`w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors ${
                    themeId === themeOption.id
                      ? 'bg-primary-50 dark:bg-primary-900/20 text-primary-600 dark:text-primary-400'
                      : 'hover:bg-gray-50 dark:hover:bg-secondary-700 text-gray-700 dark:text-secondary-300'
                  }`}
                >
                  {/* 主题色彩预览 */}
                  <div className="flex gap-1">
                    <div 
                      className="w-3 h-3 rounded-full border border-gray-200 dark:border-secondary-600"
                      style={{ backgroundColor: themeOption.colors.primary[500] }}
                    ></div>
                    <div 
                      className="w-3 h-3 rounded-full border border-gray-200 dark:border-secondary-600"
                      style={{ backgroundColor: themeOption.colors.secondary[500] }}
                    ></div>
                  </div>
                  
                  <span className="flex-1 text-left">{themeOption.name}</span>
                  
                  {themeId === themeOption.id && (
                    <i className="i-mdi-check text-primary-500"></i>
                  )}
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default ThemeSelector;